//index.js
var util = require('../../utils/util.js')
//获取应用实例
const app = getApp()
Page({
    data: {
        motto: '工业区的洗车专家',
        userInfo: {},
        hasUserInfo: false,
        isAuthUserInfo: false,
        isBind: false,
        canIUse: wx.canIUse('button.open-type.getUserInfo'),
        // 多列选择器(二级联动)列表设置,及初始化
        serverIndex: null,
        serverInfoList: [],
        timeArray: [
            [],
            []
        ],
        serverTimeList: [],
        washCarTime: null,
        timeIndex: null,
        washAddress: null,
        showCallModal: false, //弹出框默认隐藏
        serverPhone: '0577-88837590'
    },
    showCall() {
        this.setData({
            showCallModal: true
        })
    },
    showPayment() {
        wx.navigateTo({
            url: '/order/payment/payment',
        })
    },
    selectCallMethos(e) {
        console.log(e)
        let that = this;
        let method = e.target.dataset.method;
        if (method == 'okCall') {
            wx.makePhoneCall({
                phoneNumber: that.data.serverPhone,
            })
        } else if (method != 'cancelCall') {
            return;
        }
        this.setData({
            showCallModal: false
        })
        return;
    },
    showRAMsg(e) {
        console.log(e);
        //认证检查
        if (app.globalData.isAuthUserInfo != true) {
            //显示认证提示
            app.showAuthUserInfo();
            return;
            //注册绑定检查
        } else if (wx.getStorageSync('isBind') != true) {
            //显示认证提示
            wx.showModal({
                title: '提示',
                content: '你的账号未注册,请先注册',
            })
            return;
        }
        return false;
    },
    //选择车辆
    chooseMyCar() {
        if (wx.getStorageSync('isBind') != true) {
            //显示认证提示
            wx.showModal({
                title: '提示',
                content: '你的账号未注册,请先注册',
            })
            return;
        }
        wx.setStorageSync('chooseCar', this.data.chooseCar);
        wx.setStorageSync('washCarTime', this.data.washCarTime);
        wx.setStorageSync('serviceInfo', this.data.serviceInfo);
        wx.setStorageSync('washCarAddress', this.data.washCarAddress);
        wx.setStorageSync('washAddress', this.data.washAddress);
        var url = '/order/mycar/mycar'
        app.tempData.isChoose = true
        wx.navigateTo({
            url: url,
        })
    },
    /**
  * 生命周期函数--监听页面卸载
  */
    onUnload(){
        this.cleanFormData();
    },
     /**
  * 生命周期函数--监听页面隐藏
  */
    // onHide(){
    //     this.cleanFormData();
    // },
    //提交事件
    formSub: function(e) {
        var that = this;
        var data = this.data;
        var resMsg = this.checkFormParams(data);
        if (resMsg != "true") {
            wx.showModal({
                title: '警告',
                content: resMsg,
            })
            return 0;
        }
        wx.showModal({
            title: '确定提交订单?',
            content: '确定提交订单',
            success: function(res) {
                if (res.confirm) {
                    console.log('用户点击确定')
                    that.doRequestPayment(data);
                    that.cleanFormData();
                } else if (res.cancel) {
                    console.log('用户点击取消')
                    return;
                }
            }
        })
    },
    //发起下单请求
    doRequestPayment(data) {
        // util.log(data.serviceInfo);
        var param = {
            userId: data.userId,
            date: data.washCarTime.date,
            serverType: data.serviceInfo.id,
            washTime: data.washCarTime.id,
            money: data.serviceInfo.price,
            carInfo: data.myCarInfo,
            washAddress: data.washCarAddress+data.washAddress
        };
        console.log(param);
        let url = "/order/washCarOrder/addWashCarOrder";
        app.post(url, param, res => {
            util.log(res);
            if (res.code == 0) {
                console.log(res.data);
                //调起微信支付
                wx.requestPayment({
                    timeStamp: res.data.timeStamp,
                    nonceStr: res.data.nonceStr,
                    package: res.data.package,
                    signType: res.data.signType,
                    paySign: res.data.paySign,
                    success: function(result) {
                        util.log(result);
                        //支付成功
                        wx.navigateTo({
                            url: '/order/payment/payment',
                        })
                    },
                    fail: function(result) {
                        util.log(result);
                        //支付失败
                        wx.showModal({
                            title: '支付失败',
                            content: '',
                        })
                    }
                })
            }

        });
    },
    //检查订单信息
    checkFormParams(data) {
        if (!data.userId) {
            return "用户信息为空,请重新登录";
        } else if (!data.serviceInfo) {
            return "服务信息不能为空";
        } else if (!data.washAddress) {
            return "洗车地点不能为空";
        } else if (!data.myCarInfo) {
            return "车辆信息不能为空";
        } else if (!data.washCarTime) {
            return "洗车时间不能为空";
        }
        return "true";
    },
    // 选择服务项目
    onServicePicker(e) {
        let val = e.detail.value;
        this.setData({
            serverIndex: val
        })
        // console.log(val)
        var serverInfoList = wx.getStorageSync('serverInfoList');
        var serviceInfo = serverInfoList[val[1]];
        serviceInfo.serverIndex = val;
        console.log(serviceInfo)
        this.setData({
            serviceInfo: serviceInfo
        });
        wx.setStorageSync('serviceInfo', serviceInfo);
    },
    //改变服务项目
    onServicePickerChange(e) {
        util.log(e)
        this.setData({
            timeIndex: e.detail.value
        })
    },
    // 选择时间
    timePicker(e) {
        let val = e.detail.value;
        console.log(val)
        let col = val[0];
        let row = val[1];
        this.setData({
            timeIndex: val
        })
        let washCarTime = this.data.serverTimeList[col][row];
        washCarTime.timeIndex = val;
        console.log(washCarTime)
        this.setData({
            washCarTime: washCarTime,
        })
        wx.setStorageSync('washCarTime', washCarTime);
    },
    //选择器中改变列
    timePickerBindchange: function(e) {
        var col = e.detail.value;
        if (e.detail.column != 0) {
            return;
        }
        console.log(e.detail)
        // var serviceTime = wx.getStorageSync('serviceTime');
        var timeArray = this.data.timeArray;
        timeArray[1] = this.data.serverTimeList[col];
        console.log(timeArray)
        this.setData({
            timeArray: timeArray
        })
        this.setData({
            timeIndex: [col, 0]
        })
    },
    gotoUserCenter() {
        if (wx.getStorageSync('isBind')) {
            wx.navigateTo({
                url: '../Personal/Personal'
            })
        } else {
            //跳转注册页面
            wx.navigateTo({
                url: '../register/register'
            })
        }
    },
    setThisPageUserInfo(res) {
        this.setData({
            userInfo: res ? res : app.globalData.userInfo,
            hasUserInfo: true,
            userId: app.globalData.user.id,
            isAuthUserInfo: app.globalData.isAuthUserInfo,
            isBind: wx.getStorageSync('isBind')
        })
    },
    // 自动获取头像信息
    setUserInfo: function() {
        let that = this;
        if (app.globalData.userInfo) {
            that.setThisPageUserInfo();
        } else if (this.data.canIUse) {
            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
            // 所以此处加入 callback 以防止这种情况
            app.userInfoReadyCallback = userInfo => {
                that.setThisPageUserInfo(userInfo);
            }
        } else {
            // 在没有 open-type=getUserInfo 版本的兼容处理
            wx.getUserInfo({
                success: res => {
                    app.globalData.userInfo = res.userInfo
                    that.setThisPageUserInfo(res.userInfo);
                }
            })
        }
    },
    onLoad: function() {
        this.setData({
            userInfo: {},
            hasUserInfo: false,
            isAuthUserInfo: false,
            isBind: false,
        })
        if (!app.globalData.hasUser) {
            app.userInfoReadyCallback = this.doInitOrder;
        } else {
            this.doInitOrder();
        }
    },
    cleanFormData(){
        wx.removeStorageSync('chooseCar');
        wx.removeStorageSync('washCarTime');
        wx.removeStorageSync('serviceInfo');
        wx.removeStorageSync('washCarAddress');
        wx.removeStorageSync('washAddress');
    },
    //设置已输入的订单表单信息
    setFormData(){
        let chooseCar = wx.getStorageSync('chooseCar');
        let washCarTime = wx.getStorageSync('washCarTime');
        let serviceInfo = wx.getStorageSync('serviceInfo');
        let washCarAddress = wx.getStorageSync('washCarAddress');
        let washAddress = wx.getStorageSync('washAddress');
        if (serviceInfo) {
            this.setData({
                serviceInfo: serviceInfo,
                serverIndex: serviceInfo.serverIndex
            })
        } if (washCarAddress) {
            this.setData({
                washCarAddress: washCarAddress,
            })
        } if (washAddress) {
            this.setData({
                washAddress: washAddress,
            })
        }
        if (washCarTime) {
            this.setData({
                washCarTime: washCarTime,
                timeIndex: washCarTime.timeIndex
            })
        }
        if (chooseCar) {
            console.log(chooseCar)
            this.setData({
                myCarInfo: chooseCar.carInfo + " " + chooseCar.color + " " + chooseCar.licence
            });
        }
    },
    doInitOrder() {
        console.log("init index page")
        this.setUserInfo(); //自动获取用户信息
        //设置已输入的订单表单信息
        this.setFormData();
        if (!wx.getStorageSync('isBind')) {
            return;
        }
        //设置选择的服务信息
        this.getServiceInfo(this.data.userId);
        //设置选择的服务时间信息
        this.getServerTimeInfo();
    },
    //获取服务时间信息
    getServerTimeInfo() {
        var url = '/service/serviceTime/findServiceTimeList';
        var that = this;
        app.getJson(url, {}, res => {
            console.log(res)
            if (res.code == 0) {
                //同步
                wx.setStorageSync('serviceTime', res.data);
                var list = [
                    [],
                    []
                ];
                let date;
                for (let i in res.data) {
                    var startTime = res.data[i].startTime;
                    var endTime = res.data[i].endTime;
                    res.data[i].name = startTime + "-" + endTime;
                    let coldate = {
                        id: res.data[i].date,
                        name: '今天'
                    }
                    if (date != res.data[i].date) {
                        date = res.data[i].date;
                        this.data.serverTimeList[date] = new Array();
                        if (res.data[i].date == 0) {
                            coldate.name = '今天'
                            list[0].push(coldate)
                        } else if (res.data[i].date == 1) {
                            coldate.name = '明天'
                            list[0].push(coldate)
                        } else if (res.data[i].date == 2) {
                            coldate.name = '后天'
                            list[0].push(coldate)
                        } else if (res.data[i].date > 2) {
                            coldate.name = res.data[i].date + '天后'
                            list[0].push(coldate)
                        }
                    }
                    res.data[i].dateName = coldate.name;
                    if (res.data[i].date == 0) {
                        list[1].push(res.data[i]);
                    }
                    // console.log(res.data[i]);
                    this.data.serverTimeList[date].push(res.data[i]);
                }
                that.setData({
                    timeArray: list
                })
                // console.log(list);
            }
        });
    },
    //获取服务类型
    getServiceInfo(userId) {
        var url = '/service/serverInfo/findServerInfoList';
        var that = this;
        app.getJson(url, {
            userId: userId
        }, res => {
            // console.log(res)
            if (res.code == 0) {
                wx.setStorageSync('serverInfoList', res.data);
                that.setData({
                    serverInfoList: [
                        [{
                            serverName: '上门服务'
                        }],
                        res.data
                    ]
                })
            }
        });
        app.getJson(url, {
            userId: userId,
            all:"all"
        }, res => {
            if (res.code == 0) {
                let map = new Map();
                for (let i in res.data) {
                    map.set(res.data[i].id, res.data[i]);
                }
                //同步保存服务类型数据
                console.log(map);
                app.globalData.serverInfoMap = map;
            }
        });
    },
    // 点击获取头像
    getUserInfo: function(e) {
        let that = this;
        console.log(e)
        if (e.detail.errMsg != "getUserInfo:ok") {
            wx.showModal({
                title: '提示',
                content: '获取用户信息失败,请检查网络后再试',
                showCancel: false
            })
            return;
        }
        app.globalData.userInfo = e.detail.userInfo
        //认证标记
        app.globalData.isAuthUserInfo = true;
        app.userInfoReadyCallback = this.doInitOrder;
        //重新登录
        app.doLogin();
    },
    //输入详细地址
    washAddressInput(e) {
        this.setData({
            washAddress: e.detail.value
        })
        wx.setStorageSync('washAddress', e.detail.value);
    },
    // 打开地图获取定位信息
    onGetAddress(e) {
        if (wx.getStorageSync('isBind') != true) {
            //显示注册提示
            wx.showModal({
                title: '提示',
                content: '你的账号未注册,请先注册',
            })
            return;
        }
        console.log(e)
        let that = this
        wx.chooseLocation({
            success(res) {
                console.log(res);
                that.setData({
                    washCarAddress: res.address, //大概地址
                })
                wx.setStorageSync('washCarAddress', res.address);
            }
        })
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {
        console.log(1111)
    },
    bindUserHeaderTap() {
        let that = this;
        wx.showActionSheet({
            itemList: ['个人中心', '清空缓存并退出', '取消'],
            success: function(res) {
                console.log(res.tapIndex)
                if (res.tapIndex == 0) {
                    that.gotoUserCenter();
                    that.cleanFormData();
                } else if (res.tapIndex == 1) {
                    app.cleanCache(that);
                } else if (res.tapIndex == 2){

                }
            },
            fail: function(res) {
                console.log(res.errMsg)
            }
        })
    }
})